package main

import (
    "net/http"
    "log"
    "time"
    "os"

    "github.com/prometheus/client_golang/prometheus/promhttp"
    "github.com/prometheus/client_golang/prometheus"
    "github.com/shirou/gopsutil/mem"

)

// 获取内存的时时使用速率 v.Total  v.Free

func main (){
    //初始化日志服务
    logger := log.New(os.Stdout, "[Memory]", log.Lshortfile | log.Ldate | log.Ltime)

    //初始一个http handler
    http.Handle("/metrics", promhttp.Handler())

    //初始化一个容器
    diskPercent := prometheus.NewGaugeVec(prometheus.GaugeOpts{
            Name: "memeory_percent_used",
            Help: "memeory use percent",
        },
        []string {"percent","ddddddd"},
    )

    free := prometheus.NewGaugeVec(prometheus.GaugeOpts{
            Name: "memeory_percent_free",
            Help: "memeory use percent",
        },
        []string {"percent"},
    )

    total := prometheus.NewGaugeVec(prometheus.GaugeOpts{
            Name: "memeory_percent_total",
            Help: "memeory use percent",
        },
        []string {"percent"},
    )

    prometheus.MustRegister(diskPercent)
    prometheus.MustRegister(free)
    prometheus.MustRegister(total)

    // 启动web服务，监听1010端口
    go func() {
        logger.Println("ListenAndServe at:localhost:1010")
        err := http.ListenAndServe(":8082", nil)
        if err != nil {
            logger.Fatal("ListenAndServe: ", err)
        }
    }()

    //收集内存使用的百分比
    for {
        logger.Println("start collect memory used percent!")
        v, err := mem.VirtualMemory()
        if err != nil {
            logger.Println("get memeory use percent error:%s", err)
        }
        usedPercent := v.UsedPercent
        freePercent := v.Free
        totalPercent := v.Total
        logger.Println("get memeory use percent:", usedPercent, freePercent,v.Total)
        diskPercent.WithLabelValues("usedMemory","bbbbbb").Set(usedPercent)
        free.WithLabelValues("free").Set(float64(freePercent))
        total.WithLabelValues("total").Set(float64(totalPercent))
        time.Sleep(time.Second*2)
    }
}